package com.clss.webrtclibrary;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * kurento处理所有的信令交互
 * @author liuv
 * @date 2018/5/2
 */

public class KurentoServer implements SignalingAnswerWatcherDog.SignalingAnswerOutTimeListener{
    private static final String TAG = "KurentoServer";

    public static final String WEBRTC_TYPE = "webrtc_type";
    /** 只接收 */
    public static final int WEBRTC_TYPE_RECV = 2;
    /** 只发布 */
    public static final int WEBRTC_TYPE_SEND = 3;
    /** 发布并接收 */
    public static final int WEBRTC_TYPE_SENDRECV = 4;
    /** 播放视频 */
    public static final int WEBRTC_TYPE_PLAY_RECORD = 5;
    /** 按级别依次监听视频 */
    public static final int WEBRTC_TYPE_COMMAND = 6;
    /** 作为观察者，按级别依次监听视频，自己选择是否加入视频 */
    public static final int WEBRTC_TYPE_COMMAND_LEADER = 7;

    public static final int REMOTE_VIDEO_MAX = 8;

    private static final int TIMER_INTERVAL = 30 * 1000;

    private final String WebRTC = "WebRTC";
    private final String PUBLISHER_VIEWER = "publisher_viewer";
    private final String PUBLISHER = "publisher";
    private final String VIEWER = "viewer";

    private IKurentoGatewayCallback mIKurentoGatewayCallback;
    private String mMyId, mPlayer;
    private List<PeerConnection.IceServer> mIceServers;
    private MediaInfoBean mMediaInfoBean;
    private Gson mGson = new Gson();
    private KurentoPeerManager mKurentoPeerManager;
    private List<KurentoSignallingBean.DataBean> mPublisherList = new ArrayList<>();
    private List<KurentoSignallingBean.DataBean> mWaitPublisherList = new ArrayList<>();
    private Context mContext;
    private int mType;
    private IPlayRecordCallback mIPlayRecordCallback;
    private boolean mNetworkIsDisconnect = false;
    private AppRTCAudioManager mAudioManager = null;
    private int mMaxVideo = REMOTE_VIDEO_MAX + 1;
    private Handler mHandler = new Handler();
    private int mTimeCount = 0;
    private SignalingAnswerWatcherDog mDog = new SignalingAnswerWatcherDog(this);
    private AppRTCAudioManager.AudioDevice mCurrentAudioDevice;

    private Runnable mTimerRunnable = new Runnable() {
        @Override
        public void run() {
            mTimeCount++;
            if (mTimeCount%30 == 29) {
                sendRoomPingMessage();
            }
//            if (mKurentoPeerManager != null && BuildConfig.DEBUG){
//                mKurentoPeerManager.checkPeerConnectionStatus();
//            }
            mHandler.postDelayed(mTimerRunnable, 1000);
        }
    };
    /**
     * 本机画面是否发布
     */
    private WaitPublisherAdapter mWaitPublisherAdapter;
    private AlertDialog mWaitPublisherDialog;
    private String mVideoFile = "";

    public void setVideoTrackEnable(boolean enable){
        if (mKurentoPeerManager != null){
            mKurentoPeerManager.setLocalAndRemoteVideoTrackEnable(enable);
        }
    }

    public KurentoServer(Context context, int type, IKurentoGatewayCallback iKurentoGatewayCallback,
                         IPlayRecordCallback iPlayRecordCallback) {
        this(context, type, iKurentoGatewayCallback);
        mIPlayRecordCallback = iPlayRecordCallback;
    }

    public KurentoServer(Context context, int type, IKurentoGatewayCallback iKurentoGatewayCallback) {
        this.mContext = context;
        this.mIKurentoGatewayCallback = iKurentoGatewayCallback;
        this.mType = type;
        System.setProperty("java.net.preferIPv4Stack", "true");
        //从joinRoomAnswer信令返回的内容里取iceServers
        mMediaInfoBean = mIKurentoGatewayCallback.getMediaInfo();
        mAudioManager = AppRTCAudioManager.create(context);
        mAudioManager.start((selectedAudioDevice, availableAudioDevices) -> {
            mCurrentAudioDevice = selectedAudioDevice;
            Lg.i(TAG, "---selectedAudioDevice===" + selectedAudioDevice.toString());
            Lg.i(TAG, "---availableAudioDevices===" + availableAudioDevices.toString());
        });
        mWaitPublisherAdapter = new WaitPublisherAdapter(mContext, 0);
        AlertDialog.Builder waitPublisherBuilder = new AlertDialog.Builder(context);
        waitPublisherBuilder.setSingleChoiceItems(mWaitPublisherAdapter, 0, (dialog, which) -> {
            addInPublisherList(which);
            dialog.dismiss();
        });
        mWaitPublisherDialog = waitPublisherBuilder.create();
    }

    public void initializeMediaContext(PeerConnectionFactory.Options options) {
        PeerConnectionFactory.initialize(
                PeerConnectionFactory.InitializationOptions
                        .builder(mContext)
                        .createInitializationOptions()
        );
        onOpen();
    }

    public Context getContext() {
        return mContext;
    }

    /**
     * 申请加入房间成功，开始准备本地媒体流和创建sdp信息
     */
    private void createKurentoPeerManager(JsonElement data){
        if (mKurentoPeerManager == null) {
            mKurentoPeerManager = new KurentoPeerManager(this, mContext);
        }
        if (data == null){
            Lg.i(TAG, "---createKurentoPeerManager===data == null");
        }else if (data.isJsonArray()) {
            Lg.i(TAG, "---createKurentoPeerManager===data.isJsonArray");
            getPublisherFromDataArray(data);
        }else if (data.isJsonObject()){
            Lg.i(TAG, "---createKurentoPeerManager===data.isJsonObject");
            KurentoSignallingBean.DataBean dataBean = mGson.fromJson(data, KurentoSignallingBean.DataBean.class);
            mPublisherList.add(dataBean);
        }
        switch (mType){
            case WEBRTC_TYPE_RECV:
                if (mPublisherList.size() > 0){
                    mKurentoPeerManager.prepareReceiveRemoteMedia(mPublisherList.get(0).getName());
                }
                break;
            case WEBRTC_TYPE_SEND:
                mKurentoPeerManager.preparePublishVideo();
                break;
            case WEBRTC_TYPE_SENDRECV:
                if (mPublisherList.size() > 0){
                    mKurentoPeerManager.prepareReceiveRemoteMedia(mPublisherList.get(0).getName());
                }
                mKurentoPeerManager.preparePublishVideo();
                break;
            case WEBRTC_TYPE_PLAY_RECORD:
                mKurentoPeerManager.startPlayRecord(mPlayer);
                break;
            case WEBRTC_TYPE_COMMAND:
                mKurentoPeerManager.preparePublishVideo();
                listenerTargetVideo();
                break;
            case WEBRTC_TYPE_COMMAND_LEADER:
                listenerTargetVideo();
                break;
            default:
        }
    }

    /** 从发布者列表里提取数据到本地 */
    private void getPublisherFromDataArray(JsonElement data){
        Type type = new TypeToken<List<KurentoSignallingBean.DataBean>>(){}.getType();
        List<KurentoSignallingBean.DataBean> dataList = mGson.fromJson(data.getAsJsonArray(), type);
        Lg.i(TAG, "---receivedNewMessage===dataList===" + (dataList != null ? dataList.size() : null));
        if (dataList == null || dataList.size() == 0){
            return;
        }
        mPublisherList.addAll(dataList);
    }

    /** 从加入房间拿到的列表里选择监听对象 */
    private void listenerTargetVideo(){
        Lg.i(TAG, "---listenerTargetVideo===");
        if (mPublisherList.size() < 1) {
            return;
        }
        for (KurentoSignallingBean.DataBean dataBean : mPublisherList) {
            if(!isMaxVideo(dataBean)){
                return;
            }
            choosePublisher(dataBean);
        }
    }

    private boolean isMaxVideo(KurentoSignallingBean.DataBean dataBean) {
        if (mType ==WEBRTC_TYPE_COMMAND_LEADER && !mIKurentoGatewayCallback.getVideoTrackEnable()){
            //未发布本地视频可以多显示一路
            if (mKurentoPeerManager.getRecivePeerConnectionMap().size() >= mMaxVideo) {
                mWaitPublisherList.add(dataBean);
                notifyWaitPublisherAdapter();
                return false;
            }

        } else {
            if (mKurentoPeerManager.getRecivePeerConnectionMap().size() >= REMOTE_VIDEO_MAX) {
                mWaitPublisherList.add(dataBean);
                notifyWaitPublisherAdapter();
                return false;
            }
        }
        return true;
    }

    private void notifyWaitPublisherAdapter() {
        mHandler.post(runnableUi);
    }

    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            mWaitPublisherAdapter.notifyDataSetChanged();
            if (mWaitPublisherList.size() == 0) {
                mWaitPublisherDialog.dismiss();
            }
        }
    };

    /** 选择监听目标的条件
     * 1.各个指挥中心
     * 2.一个组内的战友
     */
    private void choosePublisher(KurentoSignallingBean.DataBean dataBean){
        /** 如果是领导在看 */
        if (mMediaInfoBean.getPublicLevel() == 1){
            mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
        }else {
            if(dataBean.getExtraInfo() != null) {
                if (dataBean.getExtraInfo().getOrder() > 0) {
                    Lg.i(TAG, "---choosePublisher===getOrder() > 0===");
                    mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
                } else if (dataBean.getExtraInfo().getOrder() == 0 &&
                        getMediaInfoBean().getVideoGroupId() != null &&
                        getMediaInfoBean().getVideoGroupId().equals(dataBean.getExtraInfo().getVideoGroupId())) {
                    Lg.i(TAG, "---choosePublisher===getOrder() == 0===");
                    mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
                }
            }
        }
    }

    /** 获取媒体流的本地实现 */
    public IKurentoGatewayCallback getIKurentoGatewayCallbacks() {
        return mIKurentoGatewayCallback;
    }

    public List<PeerConnection.IceServer> getIceServers() {
        return mIceServers;
    }

    private void takeIceServer(List<KurentoSignallingBean.IceServersBean> iceServers){
        mIceServers = iceServers != null ?
                ConfigAndUtils.getIceServer(iceServers) :
                Collections.singletonList(
                        PeerConnection
                                .IceServer
                                .builder(mMediaInfoBean.getTurnAddress())
                                .setUsername(mMediaInfoBean.getTurnUser())
                                .setPassword(mMediaInfoBean.getTurnPassword())
                                .createIceServer());
        for (PeerConnection.IceServer iceServer: mIceServers){
            Lg.i(TAG, "---iceServer===" + iceServer.toString());
        }
    }

    /**
     * 分别处理接收到的各种信令
     */
    public void receivedNewMessage(KurentoSignallingBean receivedBean) {
        Lg.i(TAG, "---receivedNewMessage===" + receivedBean.getId());
        mDog.feedDog(receivedBean.getId());
        if (KurentoSignActionType.joinRoomAnswer.name().equals(receivedBean.getId())){
            if (TextUtils.isEmpty(receivedBean.getName())){
                if (!TextUtils.isEmpty(receivedBean.getResult())){
                    closeAllLiveVideo();
                    Lg.i(TAG, "---receivedNewMessage===" + receivedBean.getResult());
                }
            }else {
                takeIceServer(receivedBean.getIceServers());
                mMyId = receivedBean.getName();
                createKurentoPeerManager(receivedBean.getData());
            }

        }else if (KurentoSignActionType.publishAnswer.name().equals(receivedBean.getId())){
            mKurentoPeerManager.setRemoteSdp(receivedBean.getSdpAnswer(), null);

        }else if (KurentoSignActionType.iceCandidate.name().equals(receivedBean.getId())){
            mKurentoPeerManager.setRemoteIceCandidate(receivedBean.getCandidate().getSdpMid(),
                    receivedBean.getCandidate().getSdpMLineIndex(),
                    receivedBean.getCandidate().getCandidate(),
                    receivedBean.getName(),
                    !TextUtils.isEmpty(receivedBean.getPlayer()));

        }else if (KurentoSignActionType.newParticipantArrived.name().equals(receivedBean.getId())){
            KurentoSignallingBean.DataBean dataBean =
                    mGson.fromJson(receivedBean.getData(), KurentoSignallingBean.DataBean.class);
            whetherReceiveNewPublisher(dataBean);
            mIKurentoGatewayCallback.arrivedRoom(receivedBean);

        }else if (KurentoSignActionType.receiveVideoAnswer.name().equals(receivedBean.getId())){
            mKurentoPeerManager.setRemoteSdp(receivedBean.getSdpAnswer(), receivedBean.getName());

        }else if (KurentoSignActionType.participantLeft.name().equals(receivedBean.getId())){
            removeLeaverInPublisherList(receivedBean.getName());
            removeInWaitPublisherList(receivedBean.getName());
        }else if (KurentoSignActionType.createResponse.name().equals(receivedBean.getId())){
            takeIceServer(receivedBean.getIceServers());
            mPlayer = receivedBean.getPlayer();
            createKurentoPeerManager(null);

        }else if (KurentoSignActionType.startResponse.name().equals(receivedBean.getId())){
            mKurentoPeerManager.setPlayerRemoteSdpInfo(receivedBean.getSdpAnswer(), receivedBean.getPlayer());

        }else if (KurentoSignActionType.videoInfo.name().equals(receivedBean.getId())){
            if (mIPlayRecordCallback != null){
                mIPlayRecordCallback.setVideoInfo(
                        receivedBean.isSeekable(),
                        receivedBean.getInitSeekable(),
                        receivedBean.getEndSeekable(),
                        receivedBean.getVideoDuration(),
                        receivedBean.getPlayer());
            }

        }else if (KurentoSignActionType.playEnd.name().equals(receivedBean.getId())){
            if (mIPlayRecordCallback != null){
                mIPlayRecordCallback.videoIsOver();
            }

        }else if (KurentoSignActionType.listParticipantsAnswer.name().equals(receivedBean.getId())){
            mPublisherList.clear();
            mWaitPublisherList.clear();
            getPublisherFromDataArray(receivedBean.getData());
            checkDoWithoutPublisher();

        }else if (KurentoSignActionType.enableVideoNotice.name().equals(receivedBean.getId())){
            mIKurentoGatewayCallback.getMediaHandleCallback().enableVideo(receivedBean.getName());

        }else if (KurentoSignActionType.disableVideoNotice.name().equals(receivedBean.getId())){
            mIKurentoGatewayCallback.getMediaHandleCallback().disableVideo(receivedBean.getName());

        }else if (KurentoSignActionType.paramError.name().equals(receivedBean.getId())){
            mIKurentoGatewayCallback.signalingParamError(receivedBean.getResult());

        }else if (KurentoSignActionType.leaveRoom.name().equals(receivedBean.getId())){

        }else if (KurentoSignActionType.newGroupMemberArrived.name().equals(receivedBean.getId())){
            KurentoSignallingBean.DataBean dataBean =
                    mGson.fromJson(receivedBean.getData(), KurentoSignallingBean.DataBean.class);
            mMediaInfoBean.setVideoGroupId(dataBean.getExtraInfo().getVideoGroupId());
            sendQueryAllPublisher();
        } else if(KurentoSignActionType.position.name().equals(receivedBean.getId())){
            mIKurentoGatewayCallback.getVideoRoomListener().setVideoPosition(receivedBean.getPosition());
        }
    }

    public void onOpen() {
        Lg.i(TAG, "---onOpen===");
        if (mType == WEBRTC_TYPE_PLAY_RECORD){
            playRecord();
        } else {
            joinRoom();
        }

    }

    public void disconnection() {
        Lg.i(TAG, "---disconnection===");
        mNetworkIsDisconnect = true;
        mIKurentoGatewayCallback.webSocketDisconnect();
    }

    /** 发送加入房间的信令 */
    private void joinRoom(){
//        sendLeaveRoomMessage();   不在创建房间成功后马上发离开房间的信令
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.joinRoom.name());
        bean.setPin(mMediaInfoBean.getPin());
        bean.setRoom(mMediaInfoBean.getId());
        if (mType == WEBRTC_TYPE_COMMAND) {
            bean.setRole(PUBLISHER_VIEWER);
            bean.setExtraInfo(new KurentoSignallingBean.ExtraInfoBean(
                    mMediaInfoBean.getPublicLevel(),
                    mMediaInfoBean.getVideoGroupId(),
                    mMediaInfoBean.getPublisher(),
                    mMediaInfoBean.getUnitName()));
        }else if (mType == WEBRTC_TYPE_COMMAND_LEADER){
            bean.setRole(VIEWER);
            bean.setExtraInfo(new KurentoSignallingBean.ExtraInfoBean(
                    mMediaInfoBean.getPublicLevel(),
                    mMediaInfoBean.getVideoGroupId(),
                    mMediaInfoBean.getPublisher(),
                    mMediaInfoBean.getUnitName()));
        }else if (mType == WEBRTC_TYPE_RECV){
            bean.setRole(VIEWER);
        }
        sendMessage(bean);
    }

    /** 指挥人员手动加入视频
     */
    public void commandLeaderJoinRoom(){
        if (mType == WEBRTC_TYPE_COMMAND_LEADER && mKurentoPeerManager != null){
            mKurentoPeerManager.preparePublishVideo();
        }
    }

    public void setVideoFile(String videoFile) {
        mVideoFile = videoFile;
    }

    /** 发送播放视频的信令 */
    private void playRecord(){
        if (mVideoFile.isEmpty()) {
            if (mMediaInfoBean.getParticipants() != null && mMediaInfoBean.getParticipants().size() > 0) {
                if (mMediaInfoBean.getParticipants().get(0).getRecords() != null && mMediaInfoBean.getParticipants().get(0).getRecords().size() > 0) {
                    mVideoFile = mMediaInfoBean.getParticipants().get(0).getRecords().get(0).getVideoFile();
                } else {
                    return;
                }
            } else {
                return;
            }
        }
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.create.name());
        bean.setVideourl(mVideoFile);
        bean.setProtocol(WebRTC);
        bean.setRole(VIEWER);
        sendMessage(bean);
    }

    /**
     * 发送本人离开房间的信令
     */
    private void sendLeaveRoomMessage(){
        Lg.i(TAG, "---sendLeaveRoomMessage===");
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setRoom(mMediaInfoBean.getId());
        bean.setId(KurentoSignActionType.leaveRoom.name());
        sendMessage(bean);
    }

    /** 查询房间内当前所有的发布者 */
    public void sendQueryAllPublisher(){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setRoom(mMediaInfoBean.getId());
        bean.setId(KurentoSignActionType.listParticipants.name());
        sendMessage(bean);
    }

    /**
     * 发送信令，所有的交互信令都通过这个方法发送
     * @param bean 信令内容实体
     */
    public void sendMessage(KurentoSignallingBean bean){
        mDog.wakeUpDog(bean.getId());
        mIKurentoGatewayCallback.getVideoRoomListener().sendLocalSign(bean);
        if (!TextUtils.isEmpty(bean.getSdpOffer())){
            Lg.i(TAG, "---视频通了===");
            mHandler.postDelayed(mTimerRunnable, 1000);
        }
    }

    /** 检查是否有要取消监听的发布者，有的话干掉他 */
    private void checkDoWithoutPublisher(){
        for (KurentoSignallingBean.DataBean dataBean : mPublisherList){
            if(!isMaxVideo(dataBean)){
                return;
            }
            if (dataBean.getExtraInfo().getOrder() == 0){
                if (TextUtils.isEmpty(mMediaInfoBean.getVideoGroupId())){
                    if (mKurentoPeerManager.getRecivePeerConnectionMap().containsKey(dataBean.getName())){
                        mIKurentoGatewayCallback.leaveRoom(dataBean.getName());
                        mKurentoPeerManager.cancelReceivePublisher(dataBean.getName());
                    }
                }else {
                    if (mMediaInfoBean.getVideoGroupId().equals(dataBean.getExtraInfo().getVideoGroupId())){
                        if (!mKurentoPeerManager.getRecivePeerConnectionMap().containsKey(dataBean.getName())){
                            mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
                        }
                    }else {
                        if (mKurentoPeerManager.getRecivePeerConnectionMap().containsKey(dataBean.getName())){
                            mIKurentoGatewayCallback.leaveRoom(dataBean.getName());
                            mKurentoPeerManager.cancelReceivePublisher(dataBean.getName());
                        }
                    }
                }
            }else {
                if (!mKurentoPeerManager.getRecivePeerConnectionMap().containsKey(dataBean.getName())) {
                    mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
                }
            }
        }
    }

    /** 是否需要监听这个新来的 */
    private void whetherReceiveNewPublisher(KurentoSignallingBean.DataBean dataBean){
        if (mType == WEBRTC_TYPE_COMMAND || mType == WEBRTC_TYPE_COMMAND_LEADER) {
            if (!isMaxVideo(dataBean)) {
                return;
            }
            mPublisherList.add(dataBean);
            choosePublisher(dataBean);
        }else if (mType == WEBRTC_TYPE_SENDRECV){
            if (mKurentoPeerManager != null &&
                    mKurentoPeerManager.getRecivePeerConnectionMap().size() < 2) {
                mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
            }
        }else if (mType == WEBRTC_TYPE_RECV){
            if (mKurentoPeerManager != null &&
                    mKurentoPeerManager.getRecivePeerConnectionMap().size() == 0) {
                mKurentoPeerManager.prepareReceiveRemoteMedia(dataBean.getName());
            }
        }else {
            Lg.i(TAG, "---mType===" + mType);
        }
    }

    /**
     * 选择要加入的视频
     */
    public void showWaitPublisherListDialog() {
        if (mWaitPublisherList.size() == 0) {
            Toast.makeText(mContext, "没有可选择的视频", Toast.LENGTH_SHORT).show();
            return;
        }
        mWaitPublisherDialog.show();
    }

    /**
     * 从等待列表中加入的视频画面
     * @param position mWaitPublisherList
     */
    public void addInPublisherList(int position){
        if(!showMaxVideoToast()){
            return;
        }
        mPublisherList.add(mWaitPublisherList.get(position));
        choosePublisher(mWaitPublisherList.get(position));
        mWaitPublisherList.remove(position);
        notifyWaitPublisherAdapter();
    }

    public boolean showMaxVideoToast() {
        if(null == mKurentoPeerManager){
            return false;
        }
        if(mType == WEBRTC_TYPE_COMMAND_LEADER && !mIKurentoGatewayCallback.getVideoTrackEnable()){
            //没有领导视频可以多显示一路
            if (mKurentoPeerManager.getRecivePeerConnectionMap().size() >= mMaxVideo) {
                Toast.makeText(mContext, "最多显示" + mMaxVideo + "个视频，请先长按屏蔽视频窗口", Toast.LENGTH_LONG).show();
                return false;
            }
        } else {
            if(mKurentoPeerManager.getRecivePeerConnectionMap().size() >= REMOTE_VIDEO_MAX){
                Toast.makeText(mContext, "最多显示" + mMaxVideo + "个视频，请先长按屏蔽视频窗口", Toast.LENGTH_LONG).show();
                return false;
            }
        }
        return true;
    }

    /** 从等待发布者列表删除不需要监听的发布者 */
    public void removeInWaitPublisherList(String name){
        if (mWaitPublisherList.size() == 0){
            return ;
        }
        for (int n = 0; n < mWaitPublisherList.size(); n++){
            if (name.equals(mWaitPublisherList.get(n).getName())){
                mWaitPublisherList.remove(n);
            }
        }
        notifyWaitPublisherAdapter();
    }
    /** 从发布者列表里删除不需要监听的发布者 */
    public void removeInPublisherList(String name){
        int position = getLeaverInPublisherListPosition(name);
        if (position >= 0){
            mWaitPublisherList.add(mPublisherList.get(position));
            mPublisherList.remove(position);
            notifyWaitPublisherAdapter();
        }
        if (mKurentoPeerManager != null) {
            mKurentoPeerManager.cancelReceivePublisher(name);
        }
        Lg.i(TAG, "---removeInPublisherList===" + mPublisherList.size());
    }
    /** 从发布者列表里删除已经离开的发布者 */
    private void removeLeaverInPublisherList(String name){
        mIKurentoGatewayCallback.leaveRoom(name);
        int leaverPosition = getLeaverInPublisherListPosition(name);
        if (leaverPosition >= 0){
            mPublisherList.remove(leaverPosition);
        }
        if (mKurentoPeerManager != null) {
            mKurentoPeerManager.cancelReceivePublisher(name);
        }
        Lg.i(TAG, "---removeLeaverInPublisherList===" + mPublisherList.size());
    }

    /** 告诉信令服务器不再监听某个发布者 */
    public void sendCancelReceiveVideo(String name){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setRoom(mMediaInfoBean.getId());
        bean.setId(KurentoSignActionType.stopReceiveVideoFrom.name());
        bean.setSender(name);
        sendMessage(bean);
    }

    private int getLeaverInPublisherListPosition(String name){
        if (mPublisherList.size() == 0){
            return -1;
        }
        for (int n = 0; n < mPublisherList.size(); n++){
            if (name.equals(mPublisherList.get(n).getName())){
                return n;
            }
        }
        return -1;
    }

    /** 关掉所有的视频 */
    public boolean closeAllLiveVideo(){
        Lg.i(TAG, "---closeAllLiveVideo===" + mNetworkIsDisconnect);
        mDog.clearDog();
        mHandler.removeMessages(0);
        sendLeaveRoomMessage();
        if (mKurentoPeerManager != null ) {
            mKurentoPeerManager.stopVideoConnection();
        }
        if (mAudioManager != null){
            mAudioManager.stop();
            mAudioManager = null;
        }
        mContext = null;
        return true;
    }

    /** 根据id查询对应的发布者name*/
    public String getNameFromId(String id){
        for (KurentoSignallingBean.DataBean dataBean : mPublisherList){
            if (id.equals(dataBean.getName())){
                return dataBean.getExtraInfo().getPublisher();
            }
        }
        return "";
    }

    /** 根据id查询对应的发布者单位和name*/
    public String getUnitAndNameFromId(String id){
        for (KurentoSignallingBean.DataBean dataBean : mPublisherList){
            if (id.equals(dataBean.getName())){
                if(TextUtils.isEmpty(dataBean.getExtraInfo().getUnitName())){
                    return dataBean.getExtraInfo().getPublisher();
                } else {
                    return dataBean.getExtraInfo().getUnitName() + "-" + dataBean.getExtraInfo().getPublisher();
                }
            }
        }
        return "";
    }

    /** 视频房间内加入心跳，防止房间5分钟没动静被回收 */
    private void sendRoomPingMessage(){
        Lg.i(TAG, "---sendRoomPingMessage===" + new Date().toString());
        KurentoSignallingBean bean = new KurentoSignallingBean();
        if (mType != WEBRTC_TYPE_PLAY_RECORD){
            bean.setRoom(mMediaInfoBean.getId());
        }
        bean.setId(KurentoSignActionType.ping.name());
        sendMessage(bean);
    }

    public void seekToTime(long time, String player){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.doSeek.name());
        bean.setPlayer(player);
        bean.setPosition(time);
        sendMessage(bean);
    }

    public void pauseVideo(String player){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.pause.name());
        bean.setPlayer(player);
        sendMessage(bean);
    }

    public void resumeVideo(String player){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.resume.name());
        bean.setPlayer(player);
        sendMessage(bean);
    }

    public void getVideoPosition(String player){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.getPosition.name());
        bean.setPlayer(player);
        sendMessage(bean);
    }

    public void stopVideo(String player){
        KurentoSignallingBean bean = new KurentoSignallingBean();
        bean.setId(KurentoSignActionType.stop.name());
        bean.setPlayer(player);
        sendMessage(bean);
    }

    public MediaInfoBean getMediaInfoBean() {
        return mMediaInfoBean;
    }

    public String getMyId() {
        return mMyId;
    }

    public boolean switchCamera() {
        if (mKurentoPeerManager == null) {
            return false;
        }else {
            return mKurentoPeerManager.switchCameraInternal();
        }
    }

    public void setPlayRecordCallback(IPlayRecordCallback iPlayRecordCallback) {
        this.mIPlayRecordCallback = iPlayRecordCallback;
    }

    public void publishConnectionInfo(String info){
        mIKurentoGatewayCallback.showConnectionInfo(info);
    }

    @Override
    public void onSignalingAnswerOutTime(String type) {
        mIKurentoGatewayCallback.signalingParamError("未收到信令:" + type);
    }

    public void onVideoState(String state){
        mIKurentoGatewayCallback.signalingParamError(state);
    }

    public AppRTCAudioManager.AudioDevice switchSoundOutput(){
        if (mCurrentAudioDevice == AppRTCAudioManager.AudioDevice.SPEAKER_PHONE){
            Lg.i(TAG, "---选了听筒发声===");
            mAudioManager.setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
            mAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.EARPIECE);
            return AppRTCAudioManager.AudioDevice.EARPIECE;
        }else if (mCurrentAudioDevice == AppRTCAudioManager.AudioDevice.EARPIECE){
            Lg.i(TAG, "---选了扬声器发声===");
            mAudioManager.setDefaultAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
            mAudioManager.selectAudioDevice(AppRTCAudioManager.AudioDevice.SPEAKER_PHONE);
            return AppRTCAudioManager.AudioDevice.SPEAKER_PHONE;
        }else {
            return AppRTCAudioManager.AudioDevice.NONE;
        }
    }

    class WaitPublisherAdapter extends ArrayAdapter<KurentoSignallingBean.DataBean>{

        public WaitPublisherAdapter(@NonNull Context context, int resource) {
            super(context, resource);
        }

        @Override
        public int getCount() {
            return mWaitPublisherList.size();
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_wait_publisher,parent,false);
            TextView textView = view.findViewById(R.id.item_wait_publisher_tv);
            textView.setText(mWaitPublisherList.get(position).getExtraInfo().getPublisher());
            return view;
        }
    }

}
